package com.dldata.devtools30.filter;

import com.alibaba.fastjson.JSON;
import com.dldata.devtools30.businessmodel.SessionUserInfoEntity;
import com.dldata.devtools30.cfg.ApplicationHome;
import com.dldata.devtools30.repository.common.CommonXmlDao;
import com.dldata.devtools30.utils.Public;
import com.dldata.devtools30.utils.RightUtil;
import com.dldata.devtools30.utils.StringUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**

 */
@WebFilter(filterName = "BaseRightFilter",urlPatterns = "/*",asyncSupported = true)
@Order(value = 1)
@Configuration
@Slf4j
public class RightFilterBase implements Filter {

    private WebApplicationContext wc;

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        
        if(StringUtil.isEmptyOrLength0(Public.sysConfig.getProperty(Public.image_url))
            ||(Public.sysConfig.getProperty(Public.image_url)!=null
                &&!Public.sysConfig.getProperty(Public.image_url).endsWith(Public.image_dir_default)
                &&!Public.sysConfig.getProperty(Public.image_url).endsWith(Public.image_dir_bi))){
            String savedir = ApplicationHome.getApplicationHome() + Public.webapp_dir_ext + Public.image_dir_default;
            Public.sysConfig.setProperty(Public.image_dir, savedir);
            new File(savedir).mkdirs();
    
            String prefix=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
            Public.sysConfig.setProperty(Public.image_url,prefix+Public.image_dir_default);
        }

        HashMap pramMap=new HashMap();
        Map<String, String[]> paraMap= request.getParameterMap();
        for (Iterator iterator = paraMap.entrySet().iterator(); iterator.hasNext(); ) {
            Map.Entry<String, String[]> next = (Map.Entry<String, String[]>)iterator.next();
            if(!StringUtil.isEmptyOrLength0(next.getValue())){
                pramMap.put(next.getKey(), StringUtils.join(next.getValue(), ","));
            }else{
                pramMap.put(next.getKey(),next.getValue());
            }
        }

        Object dlPreventCircleReq = request.getAttribute("dlPreventCircleReq");
        if(dlPreventCircleReq ==null){
            dlPreventCircleReq=0;
        }
        if(((int)dlPreventCircleReq)>3){
            response.setStatus(403);
            response.setCharacterEncoding("UTF-8");
            response.addHeader("seccess","false");
            response.addHeader("msg",java.net.URLEncoder.encode("preventcirclereq.","UTF-8"));
            response.addHeader("errorinfo","preventcirclereq.");
            response.addHeader("errorinfozh",java.net.URLEncoder.encode("preventcirclereq.","UTF-8"));
            response.setContentType("application/json;charset=UTF-8");
            HashMap hashMap=new HashMap();
            hashMap.put("seccess",false);
            hashMap.put("msg","preventcirclereq");
            response.getWriter().println(JSON.toJSONString(hashMap));
            return;
        }
        request.setAttribute("dlPreventCircleReq",((int)dlPreventCircleReq)+1);

        request.setAttribute("ctxPath",request.getContextPath());
        request.setAttribute("srcPramMap",pramMap);
        request.setAttribute("srcParaMapJSON",JSON.toJSONString(pramMap));
        request.setAttribute("srcSysConfig",Public.sysConfig);

        SessionUserInfoEntity sessionUserInfoEntity = RightUtil.getCurrentUser(request);
        request.setAttribute("sessionUserInfoEntity",sessionUserInfoEntity);
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
        log.info("过滤器初始化");
        
        wc= WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
        String[] commonbeanNames=wc.getBeanNamesForType(CommonXmlDao.class);
        for (int i = 0; i < commonbeanNames.length; i++) {
            String commonbeanName = commonbeanNames[i];
            try {
                ((CommonXmlDao)wc.getBean(commonbeanName)).refrashAllData();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }

        if(!StringUtil.isEmptyOrLength0(Public.sysConfig.getProperty("cookie_dtuser"))){
            log.info("cookie_dtuser: "+ Public.sysConfig.getProperty("cookie_dtuser"));
            Public.SESSION_USER_KEY=Public.sysConfig.getProperty("cookie_dtuser");
        }
        
    }
}